package database

import (
	"blog2/util"
	"sync"

	"github.com/go-redis/redis"
)

var (
	blogRedis     *redis.Client
	blogRedisOnce sync.Once
)

func createRedisClient(addr string) *redis.Client {
	client := redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: "", // no password set
		DB:       0,  // use default DB
	})
	pong, err := client.Ping().Result()
	if err != nil {
		util.LogRus.Error("connect redis failed")
		return nil
	}
	util.LogRus.Infof("connect to redis %s", pong)
	return client
}

func Close(client *redis.Client) {
	if client == nil {
		return
	}
	client.Close()
}

func GetBlogRedisConnection() *redis.Client {
	blogRedisOnce.Do(func() {
		if blogRedis != nil {
			return
		}
		viper := util.CreateConfig("redis")
		port := viper.GetString("blog.port")
		addr := "localhost:" + port
		util.LogRus.Infof("redis address: %s", addr)
		blogRedis = createRedisClient(addr)
	})

	return blogRedis
}
